package com.cdwh.joylife.ui.base;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.afollestad.materialdialogs.MaterialDialog;
import com.cdwh.joylife.App;
import com.cdwh.joylife.R;
import com.cdwh.joylife.presenter.PresenterImpl;
import com.cdwh.joylife.presenter.ViewInterface;
import com.cdwh.joylife.utils.ImageUtils;
import com.cdwh.joylife.utils.UiUtils;
import com.cdwh.joylife.widget.TitleBar;
import com.socks.library.KLog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.analytics.MobclickAgent;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.functions.Consumer;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;


public abstract class BaseActivity extends AppCompatActivity implements ViewInterface {

    private static final int SETTINGS_REQUEST_CODE = 2;
    protected PresenterImpl presenter;
    private MaterialDialog dialog;
    protected Map<String, Object> params;
    protected InputMethodManager inputMethodManager;
//    protected int[] payTypeImages = {R.mipmap.e_weixin_pay, R.mipmap.e_icon_alipay};
//    protected String[] payTypeTitles = UiUtils.getStringArray(R.array.pay_type);

    //    protected int[] payTypeImages = {R.mipmap.icon_weixin, R.mipmap.icon_zhifubao, R.mipmap.icon_yue};
//    protected String[] payTypeTitles = UiUtils.getStringArray(R.array.course_pay_type);
    protected RxPermissions rxPermissions;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {


        overridePendingTransition(R.anim.anim_start_in, R.anim.anim_start_out);
        super.onCreate(savedInstanceState);
        params = new HashMap<>();
        setContentView(savedInstanceState);
        rxPermissions = new RxPermissions(this);
        initToolBar();
        initData();
        App.getActivityManager().addActivity(this);

    }

    protected void startPreview(ArrayList<String> mImages, int currentItem) {
        ArrayList<String> imageUrls = ImageUtils.getImageUrls(mImages);
        PhotoPreview.builder()
                .setPhotos(imageUrls)
                .setCurrentItem(currentItem)
                .start(this);
    }

    protected void startPreview(List<String> mImages, int currentItem) {
        ArrayList<String> images = (ArrayList<String>) mImages;
        ArrayList<String> imageUrls = ImageUtils.getImageUrls(images);
        PhotoPreview.builder()
                .setPhotos(imageUrls)
                .setCurrentItem(currentItem)
                .start(this);
    }

    protected void openPhoto(final ArrayList<String> selected, final int selectCount, final boolean showCamera, final boolean showGif) {
        rxPermissions
                .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)

                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) throws Exception {
                        if (granted) { // Always true pre-M
                            // I can control the camera now
                            if (selected == null) {

                                PhotoPicker.builder()
                                        .setPhotoCount(selectCount)
                                        .setShowCamera(showCamera)
                                        .setShowGif(showGif)
                                        .setPreviewEnabled(true)
                                        .start(BaseActivity.this, PhotoPicker.REQUEST_CODE);
                            } else {

                                PhotoPicker.builder()
                                        .setPhotoCount(selectCount)
                                        .setShowCamera(showCamera)
                                        .setSelected(selected)
                                        .setShowGif(showGif)
                                        .setPreviewEnabled(true)
                                        .start(BaseActivity.this, PhotoPicker.REQUEST_CODE);
                            }
                        } else {
                            // Oups permission denied
                            showPermissionsDialog();
                        }
                    }
                });
    }

    protected void showPermissionsDialog() {
        new AlertDialog.Builder(BaseActivity.this)
                .setTitle(getString(R.string.__picker_title_settings_dialog))
                .setMessage(getString(R.string.__picker_rationale_ask_again))
                .setPositiveButton(getString(R.string.__picker_setting), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
//            // Start for result

                        startActivityForResult(intent, SETTINGS_REQUEST_CODE);
//                          startForResult(activityOrFragment, intent, settingsRequestCode);
                    }
                })
                .setNegativeButton(getString(me.iwf.photopicker.R.string.__picker_cancel), null)
                .show();
    }

//    protected void startBrowserActivity(int mode, String url) {
//
//        KLog.e("url:" + url);
//
//        if (!TextUtils.isEmpty(url)) {
//            Intent intent = new Intent(this, BrowserActivity.class);
//            intent.putExtra(BrowserActivity.PARAM_URL, url);
//            intent.putExtra(BrowserActivity.PARAM_MODE, mode);
//            intent.putExtra(SonicJavaScriptInterface.PARAM_CLICK_TIME, System.currentTimeMillis());
//            startActivityForResult(intent, -1);
//        }
//    }

    protected void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    protected void initToolBar() {

        TitleBar titleBar = (TitleBar) findViewById(R.id.titleBar);
        if (titleBar != null) {
            titleBar.init(this);
        }
        presenter = new PresenterImpl(this, this);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写。"SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this);
    }

    @Override
    public void onError(Throwable throwable, int type) {
//        if (throwable.getClass().equals(HttpException.class)) {
//            HttpException exception = (HttpException) throwable;
//            try {
//                String errorMsg = exception.response().errorBody().string();
//                KLog.e("errorMsg------>" + errorMsg);
//                if (errorMsg.startsWith("<!doctype html>")) {
//                    AppToast.makeToast("服务器内部异常");
//                } else {
//                    BaseResponse response = new Gson().fromJson(errorMsg, BaseResponse.class);
//                    String message = response.getMessage();
//                    if (message.equals("权限验证不通过")) {
//                        AppToast.makeToast(this,"登录失效，请重新登录");
//                        SPUtils.clear();
//                        App.getActivityManager().finishAll();
//                        Intent intent = new Intent(this, LoginActivity.class);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        startActivity(intent);
//                    } else {
//                        AppToast.makeToast(message);
//                    }
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//
//        } else {
//            if (throwable.getClass().equals(UnknownHostException.class)) {
//                AppToast.makeToast("没有网络！");
//            } else if (throwable.getClass().equals(SocketTimeoutException.class)) {
//                AppToast.makeToast("网络繁忙,请稍后再试~");
//            } else if (throwable.getClass().equals(NullPointerException.class)) {
//                Timber.d("空指针异常");
//            } else if (throwable.getClass().equals(ConnectException.class)) {
//                AppToast.makeToast("没有网络哦，亲~");
//            } else if (throwable.getClass().equals(IllegalStateException.class)) {
////            JsonSyntaxException
////                Timber.d("");
//                AppToast.makeToast("对不起，对于您的请求，服务器处理失败了，我们会尽快修复。");
//            } else {
//                Timber.d("未知网络错误");
//                AppToast.makeToast("未知网络错误");
//            }
//        }

    }


    protected View getRootView() {
        return ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
    }

    @Override
    protected void onDestroy() {
        presenter.cancle();
        KLog.e("cancle  net ");
        App.getActivityManager().removeActivity(this);
        super.onDestroy();
    }

    protected abstract void setContentView(Bundle savedInstanceState);


    protected abstract void initData();

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        switch (id) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                KLog.d("按下返回键");
                finish();

                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.anim_close_in, R.anim.anim_close_out);
    }

    public void showDialog(String msg, boolean cancelable) {
        dialog = new MaterialDialog.Builder(this)
                .content(msg)
                .cancelable(cancelable)
                .progress(true, 0).show();
        dialog.show();
    }

    public void disDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen"); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息。"SplashScreen"为页面名称，可自定义
        MobclickAgent.onPause(this);
    }

    protected void setLinearLayoutManagerVertical(RecyclerView recyclerView) {

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
    }

    protected void setLinearLayoutManagerHorizontal(RecyclerView recyclerView) {

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);
    }

    protected void addItemDecoration(RecyclerView recyclerView) {
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration
                .Builder(this).color(UiUtils.getColor(R.color.color_dedede)).build());
    }

    protected void addItemDecoration(RecyclerView recyclerView, int leftMargin, int rightMargin) {
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration
                .Builder(this).margin(leftMargin, rightMargin).color(UiUtils.getColor(R.color.color_dedede)).build());
    }


    protected void setGridLayoutManager(RecyclerView recyclerView, int spanCount) {

        GridLayoutManager manager = new GridLayoutManager(this, spanCount);
        recyclerView.setLayoutManager(manager);
    }

    /**
     * 设置隐藏标题栏
     *
     * @param activity
     */
    protected void setNoTitleBar(Activity activity) {
        activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    /**
     * 设置全屏
     *
     * @param activity
     */
    protected void setFullScreen(Activity activity) {
        activity.getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 取消全屏
     *
     * @param activity
     */
    protected void cancelFullScreen(Activity activity) {
        activity.getWindow().clearFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    protected void setBarTranslucent() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 设置状态栏透明
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }
}
